package com.demo.api;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

import com.jfinal.core.JFinal;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PathKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.demo.media.RecevieMedia;

import org.apache.log4j.Logger;

import com.demo.util.PropertiesHelper;
import com.demo.util.ToolString;
import com.demo.util.Upload;
import com.alibaba.fastjson.JSONObject;

public class MediaApi {
	private static String filePath = "";
	private static String url = "";
	private static String AppSecret = "";
	private static String AppId = "";
	
	private static Logger log = Logger.getLogger(MediaApi.class);
	static {
		Properties r = PropertiesHelper.loadProperty("/weixin.properties");
		if (!r.isEmpty()) {
			try {
				filePath = r.getProperty("filePath");
				url = r.getProperty("wxmediaUrl");
				AppSecret = r.getProperty("AppSecret");
				AppId = r.getProperty("AppId");
			
				if (!url.endsWith("/"))
					url = url + "/";
				filePath = JFinal.me().getContextPath() + "/" + filePath;
			} catch (Exception e) {
				Logger.getLogger(Upload.class).error("无法读取参数", e);
			}
		} else {
			Logger.getLogger(Upload.class).error("无法读取 weixin.properties");
		}
	}
	/**
	 * 上传媒体文件
	 * 
	 * @param accessToken 接口访问凭证
	 * @param type 媒体文件类型（image、voice、video和thumb）
	 * @param mediaFileUrl 媒体文件的url
	 */
	public static RecevieMedia uploadMedia(String type, String mediaFileUrl) {
		RecevieMedia recevieMedia = null;
		String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
		// 拼装请求地址
		String uploadMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
		uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		// 定义数据分隔符
		String boundary = "------------7da2e536604c8";
		try {
			URL uploadUrl = new URL(uploadMediaUrl);
			HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
			uploadConn.setDoOutput(true);
			uploadConn.setDoInput(true);
			uploadConn.setRequestMethod("POST");
			// 设置请求头Content-Type
			uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			// 获取媒体文件上传的输出流（往微信服务器写数据）
			OutputStream outputStream = uploadConn.getOutputStream();

            URL mediaUrl = new URL(mediaFileUrl);
			HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
			meidaConn.setDoOutput(true);
			meidaConn.setRequestMethod("GET");

			// 从请求头中获取内容类型
			String contentType = meidaConn.getHeaderField("Content-Type");
			// 根据内容类型判断文件扩展名
			String fileExt = ToolString.getFileExt(contentType);
			// 请求体开始
			outputStream.write(("--" + boundary + "\r\n").getBytes());
			outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
			outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());

            // 获取媒体文件的输入流（读取文件）
			BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				// 将媒体文件写到输出流（往微信服务器写数据）
				outputStream.write(buf, 0, size);
			}
			// 请求体结束
			outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
			outputStream.close();
			bis.close();
			meidaConn.disconnect();

            // 获取媒体文件上传的输入流（从微信服务器读数据）
			InputStream inputStream = uploadConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			uploadConn.disconnect();

			// 使用JSON-lib解析返回结果
			JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
			recevieMedia = new RecevieMedia();
            recevieMedia.setErrcode(jsonObject.getString("errcode"));
            recevieMedia.setErrmsg(jsonObject.getString("errmsg"));
            recevieMedia.setType(jsonObject.getString("type"));
            // type等于thumb时的返回结果和其它类型不一样
			if ("thumb".equals(type)){
				recevieMedia.setMedia_id(jsonObject.getString("thumb_media_id"));
			}else{
				recevieMedia.setMedia_id(jsonObject.getString("media_id"));
			}
			recevieMedia.setCreated_at(jsonObject.getString("created_at"));
		} catch (Exception e) {
			recevieMedia = null;
			log.error("上传媒体文件失败：{}", e);
		}
		return recevieMedia;
	}

	/**
	 * 下载媒体文件
	 * 
	 * @param accessToken 接口访问凭证
	 * @param mediaId 媒体文件标识
	 * @return
	 */
	public static String getMedia(String mediaId, String msgtype) {
		String savePath=filePath;
		String filePath = null;
		String filename=null;
		String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
		// 拼接请求地址
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestMethod("GET");  
	        conn.setDoInput(true);  
	        conn.setDoOutput(true);  
			if (!savePath.endsWith("/")) {
				savePath += "/";
			}
			// 根据内容类型获取扩展名
			conn.getContentType();

			String fileExt = ToolString.getFileExt(conn.getHeaderField("Content-Type"));
			System.out.println("============2======"+fileExt);
			// 将mediaId作为文件名
			filePath =PathKit.getWebRootPath() +savePath + mediaId + fileExt;
			filename=savePath+mediaId+fileExt;
			 
			System.out.println("============2======"+PathKit.getWebRootPath() +"/"+filename );
			File dirFile = new File(PathKit.getWebRootPath()+savePath);
	        boolean bFile = false;
	            bFile = dirFile.exists();
	            if(bFile != true){
	                bFile = dirFile.mkdir();
	            }
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();

			conn.disconnect();

			log.info("下载媒体文件成功，filePath=" + filename);
		} catch (Exception e) {
			filename = null;
			log.error("下载媒体文件失败：{}", e);
		}
		return filename;
	}
	
	


	public static void main(String args[]) {
		// 获取接口访问凭证
        System.out.println("asdasd");
        String accessToken= AccessTokenApi.getAccessToken().getAccessToken() ;
		 System.out.println(accessToken);
		/**
		 * 上传多媒体文件
		 */
//		RecevieMedia recevieMedia = uploadMedia(accessToken, "voice", "http://hnhxoa.nat123.net/uploadfile/20141111105545_170.png");
//		System.out.println(recevieMedia.getMedia_id());
//		System.out.println(recevieMedia.getType());
//		System.out.println(recevieMedia.getCreated_at());

		/**
		 * 下载多媒体文件
		 */
		getMedia("kcP5z1p78eAKVV9ztsK9o6AcykZr83DaxlbUOqOFPZlg_SQWh9nQLDJRpoSq1pKC", "");
	}
}
